//
//  NMAwrBlock.m
//  podrow
//
//  Created by Michael Xu on 4/24/14.
//  Copyright (c) 2014 podrow. All rights reserved.
//

#import "NMPodrow.h"
#import "NMDeviceInfo.h"
#import "NMAwrBlock.h"
#import "AFNetworking.h"
#import "NSData+Hash.h"
#import "OpenUDID.h"
#import "NSData+Base64.h"
#import "NSMutableDictionary+UrlGenerate.h"
#import <CommonCrypto/CommonCryptor.h>

@implementation NMAdwoModel
@end

@implementation NMAwrBlock

+ (void)startRequestWithBlock:(ServerResponseBlock) serverResponseBlock
{
    NSNumber *jailbroken = [NSNumber numberWithBool:[NMDeviceInfo isJailBroken]];
    NSNumber *tracking = [NSNumber numberWithBool:[NMDeviceInfo isTrackingLimited]];

    NSString *uri = [NMRowBase doCipher:@"/kIR5qove+TxakiHs5QCwme+Djjgy4OnSHCLd1c78Wp+UJBI1FYUINHbkRENJQbcjQT5EVBXnhnd9qVfTEasNg==" key:@"3Gfbmv6mR9Lh6C4vR3pA4TpX" operation:kCCDecrypt];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:uri]];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json; encoding=utf-8" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    NSString *ua = [NSString stringWithFormat:@"%@ %@ (%@; %@; %@)", [NMDeviceInfo getBundleId], [NMDeviceInfo getAppVersion], [NMDeviceInfo getOSVersion], [NMDeviceInfo getMachineDetail], [NMDeviceInfo getLanguage]];
    [request setValue:ua forHTTPHeaderField:@"User-Agent"];
    [request setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:24];
    
    [dic setObject:[NMDeviceInfo getIDFA] forKey:@"idfa"];
    [dic setObject:jailbroken forKey:@"jailbreak"];
    [dic setObject:[NMDeviceInfo getOSVersion] forKey:@"os_version"];
    [dic setObject:[NMDeviceInfo getLanguage] forKey:@"language"];
    [dic setObject:[NMDeviceInfo getMAC] forKey:@"imei"];
    [dic setObject:@"apple" forKey:@"manufacture"];
    [dic setObject:[NMDeviceInfo getDeviceModel] forKey:@"model"];
    [dic setObject:tracking forKey:@"idfa_open"];
    
    NSData *key = [NSData dataFromBase64String:[UserInfo sharedInstance].AWR_APPKEY];
    NSString *openUDID = [OpenUDID value];
    NSString *did = [[self class] DESEncrypt:openUDID key:key];
    [dic setObject:did forKey:@"deviceid"];
    [dic setObject:openUDID forKey:@"openid"];
    
    NSMutableDictionary *requestDic = [NSMutableDictionary dictionaryWithCapacity:24];
    [requestDic setObject:dic forKey:@"device"];
    [requestDic setObject:@"1" forKey:@"nettype"];
    [requestDic setObject:[NMDeviceInfo getBundleId] forKey:@"bundle_id"];
    [requestDic setObject:[UserInfo sharedInstance].AWR_APPID forKey:@"public_id"];
    [requestDic setObject:[NMDeviceInfo getAppVersion] forKey:@"app_version"];
    [requestDic setObject:[NSArray arrayWithObjects:[UserInfo sharedInstance].USERID, nil] forKey:@"keywords"];
    
    NSData *requestData =  [NSJSONSerialization dataWithJSONObject:requestDic options:0 error:nil];
    [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)requestData.length] forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:requestData];
    
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSError *error;
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:operation.responseData
                                                             options:NSJSONReadingMutableLeaves
                                                               error:&error];
        
        if (error) {
            serverResponseBlock(nil, error);
        }
        else {
            if (dict != nil) {
                int code = [[dict objectForKey:@"errorcode"] intValue];
                if (code == 0) {
                    NSArray *array = [dict objectForKey:@"applist"];
                    NSDictionary *reward = [dict objectForKey:@"appDecision"];
                    NSInteger ratio = [[reward objectForKey:@"tradeRatio"] integerValue];
                    NSMutableArray *ret = [[NSMutableArray alloc] init];
                    for (NSDictionary *data in array) {
                        NMAdwoModel *app = [[NMAdwoModel alloc] init];
                        [app setBrief_intro:[data objectForKey:@"brief_intro"]];
                        [app setAdv_id:[data objectForKey:@"adv_id"]];
                        [app setAdv_type:[data objectForKey:@"adv_type"]];
                        [app setIcon_url:[data objectForKey:@"icon_url"]];
                        [app setPackage:[data objectForKey:@"package"]];
                        [app setOpen_type:[data objectForKey:@"open_type"]];
                        [app setBonus_intro:[data objectForKey:@"bonus_intro"]];
                        [app setSize:[data objectForKey:@"size"]];
                        [app setVersion:[data objectForKey:@"version"]];
                        [app setBundleid:[data objectForKey:@"bundleid"]];
                        [app setIssetup:[data objectForKey:@"issetup"]];
                        [app setAd_url:[data objectForKey:@"ad_url"]];
                        [app setD_confirm:[data objectForKey:@"d_confirm"]];
                        [app setName:[data objectForKey:@"name"]];
                        [app setDetail_intro:[data objectForKey:@"detail_intro"]];
                        [app setCharge_url:[data objectForKey:@"charge_url"]];
                        [app setBeacon_urls:[data objectForKey:@"beacon_urls"]];
                        [app setPointnum:[[data objectForKey:@"pointnum"] integerValue] * ratio];
                        
                        [ret addObject:app];
                    }
                    serverResponseBlock(ret, nil);
                }
                else {
                    NSError *error = [NSError errorWithDomain:@"" code:code userInfo:nil];
                    serverResponseBlock(nil, error);
                }
            }
            else {
                serverResponseBlock(nil, nil);
            }
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        serverResponseBlock(nil, error);
    }];
    
    [operation start];
}

+ (void)startRequestAd:(id) model
{
    if ([model isKindOfClass:[NMAdwoModel class]]) {
        NMAdwoModel *m = (NMAdwoModel *) model;

        NSURL *szURL = [NSURL URLWithString:m.charge_url];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:szURL];
        NSString *ua = [NSString stringWithFormat:@"%@ %@ (%@; %@; %@)", [NMDeviceInfo getBundleId], [NMDeviceInfo getAppVersion], [NMDeviceInfo getOSVersion], [NMDeviceInfo getMachineDetail], [NMDeviceInfo getLanguage]];
        [request setValue:ua forHTTPHeaderField:@"User-Agent"];
        [request setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
        
        AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
        [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSInteger code = [[[NSString alloc] initWithData:operation.responseData encoding:NSUTF8StringEncoding] integerValue];
            if (code == 1) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:m.ad_url]];
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        }];
        
        [operation start];
    }
}

const Byte vector[] = {1,2,3,4,5,6,7,8};

+ (NSString *)DESEncrypt:(NSString *)encryptText key:(NSData *)desKey
{
    NSString *encryptResust = nil;
    
    NSData *encryptData = [encryptText dataUsingEncoding:NSUTF8StringEncoding];
    unsigned char buffer[1024];
    memset(buffer, 0, sizeof(char));
    size_t numBytesEncrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmDES,
                                          kCCOptionPKCS7Padding,
                                          [desKey bytes], kCCKeySizeDES,
                                          vector,
                                          [encryptData bytes], [encryptData length],
                                          buffer, 1024,
                                          &numBytesEncrypted);
    if (cryptStatus == kCCSuccess) {
        NSData *data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesEncrypted];
        encryptResust = [data base64EncodedString];
    }
    return encryptResust;
}

@end
